import {ElMessageBox} from 'element-plus'
import {getCurrentInstance} from "vue"

/**
 * 成功提示
 * @param content
 * @param title
 */
export function useSuccessDialog(content: string, title: string = '系统提醒'): Promise<boolean> {
    return new Promise(resolve => {
        ElMessageBox.confirm(content, title ? title : '系统提醒',
            {
                customClass: "app-modal-message",
                showCancelButton: false,
                confirmButtonText: "确定",
                type: 'success',
            }
        )
            .then(() => resolve(true))
            .catch(() => resolve(false))
    })
}


/**
 * 警告提示
 * @param content
 * @param title
 */
export function useWarningDialog(content: string, title: string = '系统提醒'): Promise<boolean> {
    return new Promise(resolve => {
        ElMessageBox.confirm(content, title ? title : '系统提醒',
            {
                customClass: "app-modal-message",
                showCancelButton: false,
                confirmButtonText: "确定",
                type: 'warning',
            }
        )
            .then(() => resolve(true))
            .catch(() => resolve(false))
    })
}


/**
 * 警告错误
 * @param content
 * @param title
 */
export function useErrorDialog(content: string, title: string = '系统提醒'): Promise<boolean> {
    return new Promise(resolve => {
        ElMessageBox.confirm(content, title ? title : '系统提醒',
            {
                customClass: "app-modal-message",
                showCancelButton: false,
                confirmButtonText: "确定",
                type: 'error'
            }
        )
            .then(() => resolve(true))
            .catch(() => resolve(false))
    })
}


/**
 * 确认操作
 * @param msg
 * @param title
 * @param option
 */
export function useConfirmDialog(msg: string, title: string = '操作提醒', option: any = {}) {
    return new Promise(resolve => {
        ElMessageBox.confirm(
            msg, title,
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                ...option
            }
        ).then(() => resolve(true)).catch(() => resolve(false))
    })
}


/**
 * 获取当前ElMessageBox弹出层组件库销毁实例
 */
export function useCloseMessageBox(): () => void {
    const instance: any = getCurrentInstance()
    let page: any = instance.proxy
    let num = 0;
    while (typeof page === 'object') {
        num++
        if (page.doClose && typeof page.doClose === 'function') {
            page = page.doClose
        } else {
            page = page.$parent
        }
        if (num > 10) {
            break;
        }
    }
    return typeof page === 'function' ? page : ElMessageBox.close
}